import { Button, message, Modal, Upload } from "antd";
import { connect } from "dva";
import moment from "moment";
import React from "react";
import * as XLSX from 'xlsx';
import enums from "./enums";
import { getDicByKeyValue } from '@/components/common/PateoForm/utils/helper';
import { getToken } from "@/utils/utils";
import styles from "./index.less";
import { getMd5, getKeyValueString } from '@/utils/utils';
import { windowUrl } from '../../../../public/global';
import { UploadOutlined } from '@ant-design/icons';
import { getOptAuthHeaders } from '@/utils/common'
import { fingerprintFetch } from '@/utils/request'

@connect((state) => ({
  merchantsData: state.menu.merchantsData
}))
export default class BatchImportModal extends React.PureComponent {
  state = {
    fileList: [],
    submitBntLading: false,
    filePath: "",
  };

  componentDidMount() { }

  handleSubmit = () => {
    const { changeBatchImportModalVisible, merchantsData } = this.props;
    const { filePath } = this.state;
    if (!filePath.trim()) {
      message.warning("请上传文件");
      return;
    }
    this.setState({
      submitBntLading: true,
    });
    this.props.dispatch({
      type: "creditCar/postObjWithRes",
      payload: {
        url: "/mscreditbusiness/vehicle/credit/import/excel",
        filePath,
        merchantType: merchantsData.type ?? 0
      },
      callback: (response) => {
        if (response && response.statusCode == "0") {
          message.success("操作成功,请点击[任务中心]按钮查看处理进度!");
          changeBatchImportModalVisible(true);
        } else {
          // message.error(response.statusMessage);
        }
        this.setState({
          submitBntLading: false,
        });
      },
    });
  };

  handleOnChange = (info) => {
    let tempFileList = info.fileList;
    tempFileList = tempFileList.slice(-1);
    if (info.file.status === 'uploading') {
      this.setState({
        filePath: "",
        fileList: [...tempFileList],
      });
    }
    else if (
      info.file.status === "done" &&
      info.file.response &&
      info.file.response.responseCode == "200"
    ) {
      message.success("上传成功");
      this.setState({
        filePath: info.file.response.fileRecordList[0].fileUri,
        fileList: tempFileList,
      });
    }
    else if (info.file.status === "removed") {
      this.setState({
        filePath: "",
        fileList: [],
      });
    }
    else if (
      info.file.status === "error" ||
      info.file.response.statusCode != "200"
    ) {
      message.error("上传失败");
      this.setState({
        filePath: "",
        fileList: [],
      });
    }
    this.setState({
      fileList: [...tempFileList],
    })
  };

  handleBeforeUpload = async (file, fileList) => {
    const flag = await new Promise((resolve, reject) => {
      const upload = (file2, this2) => {
        const reader = new FileReader();
        reader.onload = function (e) {
          const data = new Uint8Array(e.target.result);
          const workbook = XLSX.read(data, { type: "array" });
          const firstSheetName = workbook.SheetNames[0];
          const worksheet = workbook.Sheets[firstSheetName];
          const res = XLSX.utils
            .sheet_to_json(worksheet, { header: 1 })
            .slice(1);
          let checkFlag = false;
          res.map((item) => {
            if (!item[0]) {
              checkFlag = true;
            }

            if (!item[1]) {
              checkFlag = true;
            }

            if (!item[2]) {
              checkFlag = true;
            }

            if (!item[3]) {
              checkFlag = true;
            }
          });
          if (checkFlag) {
            resolve(false);
          } else {
            resolve(true);
          }
        };
        reader.readAsArrayBuffer(file2);
      };
      upload(file, this);
    });

    if (true) {
      this.setState({ fileList });
      return true;
    } else {
      message.error("格式错误,请重新上传");
      this.setState({ fileList: [] });
      return false;
    }
  };

  downloadFileByUrl = (url, name) => {
    let str = `${window.g.url}/mscreditbusiness/vehicle/import/excel/template/download`;
    const obj = Object.assign({}, {});
    let dataStr = getKeyValueString(obj)
    let md5 = getMd5(dataStr)
    const newOptions = {};
    newOptions.method = 'POST';
    newOptions.headers = {
      Accept: 'application/json',
      'Content-Type': 'application/json; charset=utf-8',
      OptAuthorization: `${getToken()}`,
      shaSign: md5,
    };
    fingerprintFetch(str, newOptions)
      .then(response => {
        this.setState({
          exportLoading: false,
        });
        if (response.status === 200) {
          return response.blob();
        } else {
          throw response;
        }
      })
      .then(blob => {
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = name;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
      })
      .catch(() => {
        this.setState({
          exportLoading: false,
        });
        message.error('导出失败，请稍后再试!');
      });
  }

  render() {
    const { submitBntLading, fileList } = this.state;

    const { changeBatchImportModalVisible, templateFileUrl, merchantsData } = this.props;
    const { uploadUrl = '/upload/single?bizType=m18' } = this.props;
    const url = `${windowUrl}${uploadUrl}`;
    let md5 = getMd5('bizType=m18')
    return (
      <Modal
        title="批量导入授信车辆"
        onCancel={() => changeBatchImportModalVisible(false)}
        visible={true}
        footer={[
          <Button
            key="back"
            type="ghost"
            onClick={() => changeBatchImportModalVisible(false)}
          >
            取 消
          </Button>,
          <Button
            key="submit"
            type="primary"
            loading={submitBntLading}
            onClick={() => this.handleSubmit("submit")}
          >
            提 交
          </Button>,
        ]}
      >
        <div className={styles.batchImportModal}>
          <div className={styles.publicItem}>
            <div className={styles.title}>模板:</div>
            <a
              onClick={() => {
                this.downloadFileByUrl(templateFileUrl, "批量导入授信车辆模板-" +
                  moment().format("YYYY-MM-DD") +
                  ".xlsx");
              }}
            >
              下载
            </a>
          </div>
          <div className={styles.publicItem}>
            <div className={styles.title}>选择文档:</div>
            <div>
              <Upload
                onRemove={() => {
                  this.setState({
                    fileList: [],
                    filePath: "",
                    thirdCredictCarList: [],
                    checkFlag: false,
                  });
                }}
                accept={".xlsx,.xls"}
                fileList={fileList}
                beforeUpload={(file, fileList) =>
                  this.handleBeforeUpload(file, fileList)
                }
                action={url}
                headers={{
                  OptAuthorization: `${getToken()}`,
                  ...getOptAuthHeaders(),
                  shaSign: md5,
                }
                }
                // data={{
                //   merchantType: merchantsData.type ?? 0
                // }}
                multiple={false}
                onChange={(info) => {
                  this.handleOnChange(info);
                }}
              >
                {fileList.length === 0 ? (
                  <Button size="small" icon={<UploadOutlined />} type="primary">
                    上传
                  </Button>
                ) : null}
              </Upload>
            </div>
          </div>
        </div>
      </Modal>
    );
  }
}
